package com.cyj.comment.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cyj.comment.dto.UserDTO;
import com.cyj.comment.entity.Follow;
import com.cyj.comment.entity.User;
import com.cyj.comment.mapper.FollowMapper;
import com.cyj.comment.service.FollowService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cyj.comment.service.UserService;
import com.cyj.comment.utils.Result;
import com.cyj.comment.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author chixiaowai
 * @since 2023-04-04
 */
@Service
@Slf4j
public class FollowServiceImpl extends ServiceImpl<FollowMapper, Follow> implements FollowService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private UserService userService;

    @Override
    public Result follow(Long followUserId, Boolean isFollow) {
        //获取登录用户
        Long userId = UserHolder.getUser().getId();
        if (userId == null) {
            return Result.fail("未登录");
        }
        String key = "follows:" + userId;
        //判断是否已关注
        if (isFollow) {
            //未关注
            Follow follow = new Follow();
            follow.setUserId(userId);
            follow.setFollowUserId(followUserId);
            boolean success = save(follow);
            //存入redis的set中
            if (success){
                stringRedisTemplate.opsForSet().add(key, followUserId.toString());
            }

        } else {
            //已关注
            LambdaQueryWrapper<Follow> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Follow::getUserId, userId).eq(Follow::getFollowUserId, followUserId);
            boolean success = remove(queryWrapper);
            if (success){
                //从redis中的set中移除用户
                stringRedisTemplate.opsForSet().remove(key, followUserId.toString());
            }
        }
        return Result.ok();
    }

    @Override
    public Result isFollow(Long followUserId) {
        //获取登录用户
        Long userId = UserHolder.getUser().getId();
        if (userId == null) {
            return Result.fail("未登录");
        }
        LambdaQueryWrapper<Follow> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Follow::getUserId, userId).eq(Follow::getFollowUserId, followUserId);
        int count = count(queryWrapper);
        return Result.ok(count > 0);
    }

    @Override
    public Result followCommon(Long followUserId) {
        //当前登录用户
        Long userId = UserHolder.getUser().getId();
        if (userId == null){
            return Result.fail("未登录");
        }
        String myKey = "follows:" + userId;
        //目标用户
        String followKey = "follows:" + followUserId;
        Set<String> followCommon = stringRedisTemplate.opsForSet().intersect(myKey, followKey);
        if (followCommon == null || followCommon.isEmpty()){
            return Result.ok(Collections.emptyList());
        }
        //解析共同关注的id集合
        List<Long> followCommonIds = followCommon.stream().map(Long::valueOf).collect(Collectors.toList());
        List<UserDTO> userDTOList = userService.listByIds(followCommonIds)
                .stream()
                .map(user -> BeanUtil.copyProperties(user, UserDTO.class))
                .collect(Collectors.toList());
        log.info("common:{}", userDTOList);
        return Result.ok(userDTOList);
    }

}
